#    tribalgrowth is a growth monitor for the online game Tribal Wars.
#    Copyright 2009 Nathan Michaels                                            
#                                                                              
#    This file is part of tribalgrowth.                                        
#                                                                              
#    tribalgrowth is free software: you can redistribute it and/or modify      
#    it under the terms of the GNU General Public License as published by      
#    the Free Software Foundation, either version 2 of the License, or         
#    (at your option) any later version.                                       
#                                                                              
#    tribalgrowth is distributed in the hope that it will be useful,           
#    but WITHOUT ANY WARRANTY; without even the implied warranty of            
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             
#    GNU General Public License for more details.                              
#                                                                              
#    You should have received a copy of the GNU General Public License         
#    along with tribalgrowth.  If not, see <http://www.gnu.org/licenses/>. 

from pysqlite2 import dbapi2 as db

class TribalDB (object):
    def __init__(self, fileName='tribal.db'):
        self.connection, self.cursor = self.InitConnection (fileName)
        self.fileName = fileName

    def CheckVillageTable (self, village):
        """Make sure tableName exists. If not, create it as a village."""
        ID = str (village['id'])
        x = village['x']
        y = village['y']

        tableName = 'village' + ID
        self.cursor.execute (
            '''CREATE TABLE IF NOT EXISTS %s (date INTEGER PRIMARY KEY,
                            name STRING, player STRING,
                            points INTEGER, rank INTEGER)'''%
            (tableName,))
        self.cursor.execute ('INSERT OR IGNORE INTO villages VALUES (?, ?, ?)',(ID,x,y))
        return tableName

    def AddVillageData (self, now, vill):
        """Add a village to the appropriate table."""
        tableName = self.CheckVillageTable (vill)
        self.cursor.execute ('''INSERT INTO %s VALUES (?, ?, ?, ?, ?)'''%
                             (tableName,),
                             (now, vill['name'], vill['player'], vill['points'],
                              vill['rank']))

    def InitConnection (self, fileName):
        connection = db.connect (fileName)
        cursor = connection.cursor ()
        
        # $id, $name, $x, $y, $player, $points, $rank
        cursor.execute ('''CREATE TABLE IF NOT EXISTS villages
                          (id INTEGER PRIMARY KEY, x INTEGER, y INTEGER)''')
        connection.commit()
        return connection, cursor

    def AddVillages (self, now, villages):
        """Add villages to their respective tables. Guaranteed to add all or
        none of them."""
        try:
            for village in villages:
                self.AddVillageData (now, village)
            self.connection.commit()
        except:
            self.connection.rollback()
            raise

if __name__=='__main__':
    Db = TribalDB ()
